const { defineConfig } = require('@vue/cli-service')
const TerserPlugin = require('terser-webpack-plugin')
const CompressionPlugin = require('compression-webpack-plugin')
const FileManagerPlugin = require('filemanager-webpack-plugin')
const path = require('path')
function resolve (dir) {
  return path.join(__dirname, dir)
}
module.exports = defineConfig({
  transpileDependencies: true,
  productionSourceMap: false,
  lintOnSave: process.env.NODE_ENV !== 'production',
  configureWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
      // 排除引入的包，使用cdn
      config.externals = {
        vue: 'Vue',
        'vue-router': 'VueRouter',
        vuex: 'Vuex',
        axios: 'axios',
        'element-ui': 'ELEMENT',
        nprogress: 'NProgress',
        'decimal.js': 'Decimal',
        moment: 'moment',
        echarts: 'echarts',
        lodash: '_'
      }
      // 为生产环境修改配置...
      config.plugins.push(
        new TerserPlugin({
          terserOptions: {
            compress: {
              warnings: false,
              drop_debugger: true, // 移除`debugger`
              drop_console: true, // 移除`console`
              pure_funcs: ['console.log'] // 移除`console.log`
            }
          },
          extractComments: false, // 移除注释
          parallel: true // 使用多进程并行运行来提高构建速度
        }),
        new CompressionPlugin({
          test: /\.(js|css)(\?.*)?$/i, // 需要压缩的文件正则
          threshold: 1024, // 文件大小大于这个值时启用压缩
          deleteOriginalAssets: false // 压缩后保留原文件
        }),
        new FileManagerPlugin({
          events: {
            onEnd: {
              archive: [{ source: './dist/', destination: './dist/dist.zip' }]
            }
          }
        })
      )
    }
  },
  chainWebpack (config) {
    config
      .optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial' // 仅打包最初依赖的第三方
          },
          commons: {
            name: 'chunk-commons',
            test: resolve('src/components'), // 可以自定义规则
            minChunks: 3, //  最小公共数
            priority: 5,
            reuseExistingChunk: true
          }
        }
      })
  }
})
